const express = require("express");
const router = express.Router();
const bcrypt = require("bcryptjs");

const { PrismaClient } = require("@prisma/client");

const prisma = new PrismaClient({
  log: ["query", "info", "warn"],
});


/**
 * 首页
 */
router.get("/", async (req, res, next) => {
  res.render("index", {
    title: "Express",
  });
});
/**
 * 登陆页
 */
router.get("/login", (req, res) => {
  res.render("login", {
    title: "登陆",
  });
});

/**
 * 登出
 */
router.get("/logout", (req, res) => {
  //注销session
  delete req.session.user;
  res.redirect("/");
});
/**
 * 登陆功能
 */
router.post("/login", async (req, res, next) => {
  let dbUser = await prisma.sys_user.findFirst({
    where: {
      username: req.body.username,
    },
  });
  let success = bcrypt.compareSync(req.body.password, dbUser.password);
  if (!success) {
    const error = new Error("账号和密码不匹配");
    error.status = 500;
    return next(error);
  }
  req.session.user = dbUser;
  res.redirect("/");
});

module.exports = router;
